import dayjs from "dayjs"
import { createNode } from "./createNode"
import { Visitor, Node, Context } from "./node"
import { clearDialog } from "./clearDialog"

export class LiveRoomInfoVisitor implements Visitor {
    key: string = `live_room_info`
    heart_reg: RegExp = /i\s(\d+)/
    visitNode(node: Node, ctx: Context) {
        if (!node) return;
        if (!node.visibleToUser) return;
        if (node.id && node.id.endsWith('live_red_packet_count')) {
            this.set(ctx, { redPacketCount: parseInt(node.text) })
        }
        if (node.id && node.id.endsWith('live_audience_count_text')) {
            log(`live_audience_count_text ${node.text}`)
            this.set(ctx, { online: parseInt(node.text) })
        }
        if (node.id && node.id.endsWith('live_side_bar_pendant_text_view')) {
            this.set(ctx, { category: node.text })
        }
        if (node.id && node.id.endsWith('live_red_packet_status_text')) {
            this.set(ctx, { openTime: dayjs().add(this.toSecond(node.text), 'second').format('YYYY-MM-DD HH:mm:ss'), open: () => node.clickOrRect() })
        }
        if (node.text && this.heart_reg.test(node.text)) {
            const [, count] = node.text.split(' ')
            this.set(ctx, { heartCount: parseInt(count) })
        }
        if (node.id && node.id.endsWith(`live_bottom_bar_single_icon_container`)) {
            this.set(ctx, { share: () => node.parent.parent.children[0].children[0].click() })
        }
        node.children.map(c => c.visit(this, ctx))
    }
    get(ctx: Context) {
        return ctx.get(this.key)
    }
    set(ctx: Context, val: object) {
        ctx.set(this.key, val)
    }
    toSecond(statusText?: string) {
        if (!statusText) return 0;
        const timeReg = /(\d\d)\:(\d\d)/
        const res = statusText.match(timeReg)
        if (res && res.length > 1) {
            const [, m1, s1] = res;
            const second = parseInt(m1) * 60 + parseInt(s1)
            return second;
        }
        return 0;
    }
}
export interface LiveRoomInfo {
    heartCount: number;
    online: number;
    category: string;
    // 可能没有
    openTime?: string;
    // 可能没有
    redPacketCount?: number;
    // 分享按钮
    share: () => boolean;
    // 打开按钮
    open?: () => boolean;
}
let maxWaitTime: number = 1000 * 20;
let failCount: number = 0;
export function getLiveRoomInfo(): LiveRoomInfo {
    let time = new Date().getTime()
    clearDialog()
    const statusTextNode = selector().idContains('live_red_packet_status_text').visibleToUser(true).findOne(maxWaitTime)
    if (!statusTextNode) {
        failCount += 1;
        maxWaitTime += failCount * 500;
        return;
    }
    maxWaitTime = (maxWaitTime + new Date().getTime() - time) / 2 + 3000;
    const ctx = new Context();
    const node = createNode()
    const liveInfoVisitor = new LiveRoomInfoVisitor()
    liveInfoVisitor.visitNode(node, ctx)
    const roomInfo = liveInfoVisitor.get(ctx)
    return roomInfo;
}
